package com.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.bean.Area;
import com.demo.common.Result;
import com.demo.mapper.AreaMapper;
import com.demo.service.AreaService;
import com.demo.vo.AreaVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AreaServiceImpl  extends ServiceImpl<AreaMapper, Area> implements AreaService {
	@Autowired
	AreaMapper areaMapper;
	@Override
	public Result getArea() {

		List<AreaVO> areaVOS = areaMapper.selectAreaVoList();
		List<AreaVO> areaEnd = new ArrayList<>();
		if (null!= areaVOS){
			areaEnd = addressRecursion(areaVOS,areaEnd);
			return Result.ok().success(areaEnd);
		}else{
			return Result.ok("地址列表为空");
		}
	}

	@Override
	public List<Area> getProvince() {
		return areaMapper.getProvince();
	}

	@Override
	public List<Area> getCity(Integer pid) {
		return areaMapper.getCity(pid);
	}

	@Override
	public List<Area> getArea(Integer pid) {
		return areaMapper.getArea(pid);
	}

	public static List<AreaVO>addressRecursion(List<AreaVO> areaVOList,List<AreaVO> areaEnd){
//		第一次递归,创建根目录
		if (areaEnd.size() == 0) {
			if (null != areaVOList) {
				for (AreaVO vo : areaVOList) {
					if (0 == vo.getPId()) {
						areaEnd.add(vo);
					}
				}
				AreaServiceImpl.addressRecursion(areaVOList,areaEnd);
			}
		} else {
			//非首次递归,遍历根目录,添加子节点
			for (AreaVO vo : areaEnd) {
				List<AreaVO> temporary = new ArrayList<>();
//				在所有记录中找对象子节点,并将子节点放在一个集合中
				for (AreaVO areaVO : areaVOList) {
					if (vo.getId() == areaVO.getPId())
					temporary.add(areaVO);
				}
				//两种情况,有无子节点
				if (null != temporary && temporary.size()>0){
//					有子节点,放入数据,继续递归
					vo.setAreaList(temporary);
					AreaServiceImpl.addressRecursion(areaVOList,vo.getAreaList());
				}else{
//					没有子节点,return
					return areaEnd;
				}
			}
		}
		return areaEnd;
	}


}
